package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.AgentDao;
import com.framework.entity.flow.FlowAccount;
import com.framework.entity.flow.FlowActiv;
import com.framework.entity.flow.FlowFrozenTerminal;
import com.framework.entity.flow.FlowTask;
import com.framework.entity.push.PushConfig;
import com.framework.entity.push.PushContent;
import com.framework.entity.sys.*;
import com.framework.entity.ter.StarposMercInfo;
import com.framework.entity.ter.TerMerchantReport;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.page.Query;
import com.framework.redis.util.RedisUtil;
import com.framework.service.*;
import com.framework.service.agent.SysShareImgServcie;
import com.framework.utils.*;
import com.framework.utils.StarPos.CustomerImgUpload;
import com.framework.utils.StarPos.CustomerImgUploadBean.CustomerImgUploadBean;
import com.framework.utils.StarPos.CustomerQuickRegist;
import com.framework.utils.StarPos.CustomerQuickRegistBean.CustomerSignInfo;
import com.framework.utils.StarPos.CustomerQuickRegistBean.CustomerUnsignBean;
import com.framework.utils.StarPos.StarposVerify;
import com.framework.utils.ali.AliOssUtils;
import com.framework.utils.bank.BankUtil;
import com.framework.utils.excel.ExcelUtil;
import com.framework.utils.pay.suixingfu.horfu.util.Base64Utils;
import com.framework.utils.pay.youfupay.method.SignContractMethod;
import com.framework.utils.push.JiGuangPush;
import com.framework.utils.sms.SmsType;
import com.framework.utils.string.StringUtil;
import com.framework.utils.verified.MathUtils;
import com.framework.utils.verified.Verified;
import com.framework.validator.Assert;
import com.framework.validator.ValidatorUtils;
import com.framework.view.AgentVerifiedForm;
import com.framework.view.NewAgentVerifiedForm;
import com.framework.view.PartnerView;
import com.framework.view.RegistStarposBean;
import com.google.gson.Gson;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


@Service("agentService")
public class AgentServiceImpl extends ServiceImpl<AgentDao, SysAgent> implements AgentService {

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 代理商详情
     */
    @Autowired
    private AgentInfoService agentInfoService;
    /**
     * 代理商关联表
     */
    @Autowired
    private DictService dictService;
    /**
     * 代理商关联表
     */
    @Autowired
    private TreeAgentService treeAgentService;
    @Autowired
    private BankService bankService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AgentGradeService agentGradeService;

    @Autowired
    private PushConfigService pushConfigService;

    @Autowired
    private StarposMercInfoService starposMercInfoService;
    @Autowired
    private DeptSmsService deptSmsService;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private FlowAccountService flowAccountService;

    @Autowired
    private SysBankLogoService sysBankLogoService;

    @Autowired
    private SysShareImgServcie sysShareImgServcie;

    @Autowired
    private DistribuService distribuService;

    @Autowired
    private FlowActivService flowActivService;

    @Autowired
    private TerminalInfoService terminalInfoService;

    @Autowired
    private FlowFrozenTerminalService flowFrozenTerminalService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<SysAgent> page = this.selectPage(
                new Query<SysAgent>(params).getPage(),
                new EntityWrapper<>()
        );
        return new PageUtils(page);
    }


    @Override
    public SysAgent queryByMobileAndDeptId(String phone, Long deptId) {
        if (StringUtils.isBlank(phone)) {
            throw new RRException("9000", "手机号码不能为空");
        }
        if (deptId == null) {
            throw new RRException("9000", "渠道id不能为空");
        }
        SysAgent agent = new SysAgent();
        agent.setPhone(phone);
        agent.setDeptId(deptId);
        return baseMapper.selectOne(agent);
    }

    @Override
    public SysAgent queryAgentById(Long agentId) {
        if (agentId == null || agentId == 0) {
            throw new RRException("9000", "代理商id不能为空");
        }
        SysAgent agent = new SysAgent();
        agent.setAgentId(agentId);
        return baseMapper.selectOne(agent);
    }

    @Override
    public Map<String, Object> login(String phone, String password, Long deptId) {
        Map<String, Object> map = new HashMap(3);
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(password)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = queryByMobileAndDeptId(phone, deptId);
        Assert.isNull(agent, "登录账号错误");
        //通用密码登录
        if (!StringUtils.equals("LQMHtAIXXV6pN7QTfrimRw==", password)) {
            //校验密码是否正确
            boolean isCorrect = PasswordValidate.validate(password, agent.getPassword());
            if (!isCorrect) {
                throw new RRException("9000", "登录密码错误");
            }
            int state = agent.getState();
            if (state == 2) {
                throw new RRException("9000", "您的账号已经被封禁");
            }
        }
        // 生成登录uuid，存入redis
        String uuid = UuidUtil.getUUID();
        SysBank sysBank = bankService.queryBankByAgentId(agent.getAgentId());
        redisUtil.set(uuid, phone + "," + deptId, RedisUtil.LOGIN_EXPIRATION_TIME);
        //存储基础代理商信息
        redisUtil.set(phone + "," + deptId, agent, 0);
        map.put("token", uuid);
        map.put("agent", agent);
        if (deptId.equals(1L)) {

            map.put("reserved", sysBank == null ? "1" : sysBank.getIsReserved());
        }
        // map.put("reserved", "1");
        map.put("bankName", sysBank == null ? "" : sysBank.getBankName());
        map.put("bankNo", sysBank == null ? "" : sysBank.getBankNo());
        return map;
    }

    @Override
    public Map<String, Object> getAgentByToken(String token) {
        Map<String, Object> map = new HashMap<>();
        Object phoneObj = redisUtil.get(token);
        if (phoneObj == null) {
            throw new RRException(RespCode.JWT_ERRCODE_EXPIRE);
        }
        String str = (String) phoneObj;
        String[] strs = str.split(",");
        String phone = strs[0];
        Long deptId = Long.valueOf(strs[1]);
        if (deptId == null) {
            throw new RRException(RespCode.JWT_ERRCODE_EXPIRE);
        }
        //查询基础信息
        SysAgent agent = queryByMobileAndDeptId(phone, deptId);
        if (agent != null) {
            SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agent.getAgentId());

            map.put("agent_info", agentInfo);
        }

        SysAgent baseAgent = queryBasicAgentBydeptId(agent.getDeptId());
        //平台登录
        if (baseAgent.getAgentId().equals(agent.getAgentId())) {
            map.put("parentPhone", agent.getPhone());
        } else { //普通登录
            SysAgent parentAgent = queryAgentById(agent.getPid());
            if (parentAgent == null) {
                throw new RRException("9000", "未查询到推荐人");
            }
            map.put("parentPhone", parentAgent.getPhone());
        }

        map.put("agent", agent);

        return map;
    }

    @Override
    public void outLogin(String token) {
        redisUtil.del(token);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(String phone, String password, String confPassword, String smsCode, Long pid, String name, Long deptId) {
        //数据校验
        Assert.isBlank(phone, "手机号码不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(confPassword, "确认密码不能为空");
        Assert.isBlank(smsCode, "短信验证码不能为空");
        Assert.isBlank(name, "真实姓名不能为空");
        Assert.isNull(pid, "推荐人编号不能为空");
        Assert.isNull(deptId, "渠道id不能为空");
        if (!StringUtils.equals(password, confPassword)) {
            throw new RRException("9000", "二次密码不一致");
        }

        name = Assert.hasSpace(name);

        phone = Assert.hasSpace(phone);

        //查询手机号码是否已经注册
        //SysAgent sysAgent = queryByMobile(phone);
        SysAgent sysAgent = queryByMobileAndDeptId(phone, deptId);
        if (sysAgent != null) {
            throw new RRException("9000", "此手机号码已经被注册");
        }
        SysAgent agent = queryAgentById(pid);
        //不为空，且渠道相同
        if (agent == null || !agent.getDeptId().equals(deptId)) {
            throw new RRException("9000", "推荐码错误");
        }
        SysDict sysDict = dictService.querySysDict("register", "sms_type");
        if (sysDict == null) {
            throw new RRException("9000", "错误的短信类型");
        }
        String value = sysDict.getValue() + phone;
        boolean isExist = redisUtil.hasKey(value);
        if (!isExist) {
            throw new RRException("9000", "验证码不存在或者已经失效");
        }
        String redCode = (String) redisUtil.get(value);
        if (!StringUtils.equals(smsCode, redCode)) {
            throw new RRException("9000", "验证码不正确");
        }
        //AES解密
        String textPassword = AesUtil.aesDecrypt(password);
        Assert.isBlank(textPassword, "解密错误");
        //MD5普通加密
        String MD5Password = MD5Util.string2MD5(textPassword);
        //添加代理商信息
        SysAgent addAgent = new SysAgent();
        addAgent.setDeptId(agent.getDeptId());
        addAgent.setName(name);
        addAgent.setPid(pid);
        addAgent.setPhone(phone);
        addAgent.setPassword(MD5Password);
        addAgent.setType(2);
        if (agent.getDeptId().equals(1L)) {
            addAgent.setHeadImg("https://mpos-img.oss-cn-beijing.aliyuncs.com/head/morentouxinag.png");
        } else if (agent.getDeptId().equals(889323L)) {
            addAgent.setHeadImg("https://mpos-img.oss-cn-beijing.aliyuncs.com/head/kayi_default_headimg.png");
        } else if (agent.getDeptId().equals(889324L)) {
            addAgent.setHeadImg("https://mpos-img.oss-cn-beijing.aliyuncs.com/head/xinchuang_default_headimg.png");
        } else {
            addAgent.setHeadImg("https://mpos-img.oss-cn-beijing.aliyuncs.com/head/49611057b34adad4b01acb81c0236b2.png");
        }
        addAgent.setState(1);
        insertAgent(addAgent);
        //添加代理商分润等级

        //去除短信缓存
        redisUtil.del(value);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertAgent(SysAgent agent) {
        Assert.isNull(agent, "代理商信息不能为空");
        if (agent.getDeptId() == null ||
                agent.getDeptId() == 0 ||
                StringUtils.isBlank(agent.getName()) ||
                StringUtils.isBlank(agent.getPassword()) ||
                StringUtils.isBlank(agent.getPhone()) ||
                agent.getType() == 0) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        agent.setCreateTime(new Date());
        Integer res = baseMapper.insert(agent);
        if (res == 0) {
            throw new RRException("9000", "添加代理商信息失败");
        }
        //手机号码查询
        //SysAgent newAgent = queryByMobile(agent.getPhone());
        SysAgent newAgent = queryByMobileAndDeptId(agent.getPhone(), agent.getDeptId());
        Assert.isNull(newAgent, "添加代理商信息失败");
        //添加代理商详细信息
        agentInfoService.insertAgentInfo(newAgent.getAgentId());
        //添加代理商关系信息
        treeAgentService.insertTreeAgent(newAgent.getAgentId());
        //添加代理商分润等级信息
        SysAgentGrade grade = new SysAgentGrade();
        grade.setAgentId(newAgent.getAgentId());
        grade.setCreateTime(new Date());
        grade.setThisGrade(1);
        grade.setUpdateTime(new Date());
        grade.setUpperGrade(1);
        agentGradeService.insertAgentGrade(grade);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void forgetPassword(String phone, String password, String confPassword, String smsCode, Long deptId) {
        Assert.isBlank(phone, "手机号码不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(confPassword, "确认密码不能为空");
        Assert.isBlank(smsCode, "短信验证码不能为空");
        if (!StringUtils.equals(password, confPassword)) {
            throw new RRException("9000", "二次密码不一致");
        }

        //SysAgent sysAgent = queryByMobile(phone);
        SysAgent sysAgent = queryByMobileAndDeptId(phone, deptId);
        if (sysAgent == null) {
            throw new RRException("9000", "未查询到代理商信息");
        }
        SysDict sysDict = dictService.querySysDict("forget", "sms_type");
        if (sysDict == null) {
            throw new RRException("9000", "错误的短信类型");
        }
        String value = sysDict.getValue() + phone;
        boolean isExist = redisUtil.hasKey(value);
        if (!isExist) {
            throw new RRException("9000", "验证码不存在或者已经失效");
        }
        String redCode = (String) redisUtil.get(value);
        if (!StringUtils.equals(smsCode, redCode)) {
            throw new RRException("9000", "验证码不正确");
        }
        //AES解密
        String textPassword = AesUtil.aesDecrypt(password);
        Assert.isBlank(textPassword, "加密错误");
        //MD5加盐加密
        String MD5Password = MD5Util.string2MD5(textPassword);
        sysAgent.setPassword(MD5Password);
        baseMapper.updateAgentById(sysAgent);
        //清除缓存
        redisUtil.del(value);
    }

    @Override
    public SysAgent queryAgentByToken(String token) {
        Assert.verifyToken(token);
        try {
            if (!redisUtil.hasKey(token)) {
                throw new RRException(RespCode.JWT_ERRCODE_EXPIRE);
            }
            String phone = (String) redisUtil.get(token);
            if (StringUtils.isBlank(phone)) {
                throw new RRException(RespCode.JWT_ERRCODE_EXPIRE);
            }
            Object sysObj = redisUtil.get(phone);
            if (sysObj == null) {
                throw new RRException(RespCode.JWT_ERRCODE_EXPIRE);
            }
            SysAgent SysAge = (SysAgent) sysObj;
            if (SysAge == null) {
                throw new RRException(RespCode.JWT_ERRCODE_EXPIRE);
            }
            return SysAge;
        } catch (Exception e) {
            throw new RRException("9999", e.getMessage());
        }
    }

    @Override
    public int queryAgentAddCount(Long agentId, Integer type, Integer isOwn) {
        return baseMapper.queryAgentAddCount(agentId, type, isOwn);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void agentVerified(AgentVerifiedForm form, String token) {
        // 表单校验
        ValidatorUtils.validateEntity(form);
        String phone = form.getPhone();
        String name = form.getName();
        String idCard = form.getIdCard();
        String lineNo = form.getLineNo();
        String password = form.getPassword();
        String bankNo = form.getBankNo();
        String backImg = form.getBackImg();
        String frontImg = form.getFrontImg();
        String vCode = form.getVCode();
        //身份证验证
        Verified.verfiedIDCard(name, idCard);
        //根据token查询代理商缓存
        SysAgent sysAgent = queryAgentByToken(token);
        Long agentId = sysAgent.getAgentId();
        Long deptId = sysAgent.getDeptId();
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agentId);
        //判断是否实名认证
        SysAgent agent = queryAgentById(agentId);
        String realName = agent.getRealName();
        if (StringUtils.equals("已认证", realName)) {
            throw new RRException("9000", "已经完成实名认证");
        }
        //校验卡号是否存在
        SysBank sysBank = bankService.selectBankByNo(bankNo, deptId);
        if (sysBank != null) {
            throw new RRException("9000", "银行卡号已经存在");
        }

        //校验实名认证验证码
        deptSmsService.checkSms("i_bank", phone, vCode);
        //添加银行卡信息
        SysBank bank = new SysBank();

        bank.setCreateDate(new Date());
        //查询银行的信息
        Map<String, Object> bankMap = BankUtil.getBankCodeAndName(bankNo);
        String bankCode = (String) bankMap.get("bankCode");
        String bankName = (String) bankMap.get("bankName");
        bankName = StringUtil.isEmpty(bankName) ? "其他银行" : bankName;
        bank.setPhone(phone);
        bank.setLineNo(lineNo);
        bank.setCreateDate(new Date());
        bank.setCardName(name);
        bank.setIsDefault(1);
        bank.setBankCode(bankCode);
        bank.setBankNo(bankNo);
        bank.setBankName(bankName);
        bank.setAgentId(agent.getAgentId());
        bank.setDeptId(deptId);
        bankService.insert(bank);
        //查询是否添加成功
        SysBank sysBankInfo = bankService.selectBankByNo(bankNo, deptId);
        if (sysBankInfo == null) {
            throw new RRException("9000", "银行卡信息添加失败");
        }
        //设置成默认
        if (bank.getIsDefault() == 1) {
            bankService.setDefault(sysBankInfo.getBankId());
        }
        //修改认证信息
        agentInfo.setIdCard(idCard);
        agentInfo.setIdCardBackImg(backImg);
        agentInfo.setIdCardFrontImg(frontImg);
        agentInfo.setTakePassword(password);
        agentInfoService.updateAgentInfoById(agentInfo);
        //修改认证状态
        if (deptId.equals(889324L)) {
            agent.setName(name);
        }

        agent.setRealName("已认证");
        updateAgentById(agent);
        //覆盖用户缓存
        redisUtil.set(agent.getPhone() + "," + agent.getDeptId(), agent, 0);
        //去除验证码的缓存
        redisUtil.del("verified_" + phone);
    }

    @Override
    public void updateAgentById(SysAgent agent) {
        baseMapper.updateAgentById(agent);
    }

    @Override
    public Map<String, Object> withdrawInfo(String token) {
        Map<String, Object> map = new HashedMap();
        SysAgent agent = queryAgentByToken(token);
        SysAgent sysAgent = queryAgentById(agent.getAgentId());
        if (sysAgent.getState().intValue() == 3) {

            if (sysAgent.getDeptId().equals(889323L)) {
                throw new RRException("9000", "提现休眠状态，请联系客服");
            } else {
                throw new RRException("9000", "提现暂被封禁,请联系客服");
            }

        }
        Long deptId = agent.getDeptId();
        Long agentId = agent.getAgentId();

        SysPayment sysPayment = paymentService.queryPaymentByDeptId(deptId);
        if (sysPayment.getPayType().intValue() != 3) {
            //默认银行卡信息
            SysBank bank = bankService.queryDefault(agentId);

            if (bank.getBankLogoId() == null) {
                bank = sysBankLogoService.setBankLogoId(bank);
            }
            bank.setBankLogoUrl(sysBankLogoService.selectById(bank.getBankLogoId()).getLogoUrl());
            map.put("bank", bank);
        }
        //可提余额
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agentId);
        map.put("amount", agentInfo.getAvailableAmount());
        //手续费率
        SysPayment payment = paymentService.queryPaymentByDeptId(deptId);
        if (payment == null) {
            throw new RRException("9000", "未查询到代付配置信息");

        }
        if (payment.getState().intValue() == 2) {
            throw new RRException("9000", payment.getRemark());
        }
        map.put("minAmount", payment.getMinAmount());
        map.put("chargeAmount", payment.getChargeAmount());
        map.put("chargeRate", payment.getChargeRate() + "%");

        return map;
    }

    @Override
    public Map<String, Object> queryPartnerMap(String token, String partnerCount, String thisMonthAmount, String merchantCount, String realName, String name) {
        Map<String, Object> map = new HashedMap();
        SysAgent agent = queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //直属合伙人列表
        List<PartnerView> list = baseMapper.queryPartnerList(agentId, partnerCount, thisMonthAmount, merchantCount, realName, name);
        //合伙人统计数据
        Map<String, Object> banseMap = baseMapper.queryPartnerCount(agentId);
        map.put("list", list);
        map.put("banseMap", banseMap);
        return map;
    }

    @Override
    public List<SysAgent> queryAgentByPid(String token) {
        SysAgent agent = queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        return queryAgentByPid(agentId);
    }

    @Override
    public List<SysAgent> queryAgentByPid(Long agentId) {
        return baseMapper.queryAgentByPid(agentId);
    }


    @Override
    public List<SysAgent> queryOverByPhone(String token, String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        return baseMapper.queryOverByPhone(agentId, phone);
    }

    @Override
    public Integer queryLv(String token) {
        SysAgent agent = queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        return baseMapper.queryLv(agentId);
    }

    @Override
    public Map<String, Object> queryAgentInfo(String token, String types, String time, Long agentId) {
        if (StringUtils.isBlank(types) ||
                StringUtils.isBlank(time) ||
                agentId == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        Map<String, Object> map = new HashedMap();
        if (StringUtils.equals("day", types) || StringUtils.equals("month", types)) {
            //代理商数据信息
            map = baseMapper.queryPartnerInfoMap(agentId, types, time);
        } else {
            throw new RRException("9000", "时间维度参数错误");
        }
        return map;
    }

    @Override
    public List<SysAgent> queryNormalAgentList(Long deptId) {
        return baseMapper.queryNormalAgentList(deptId);
    }

    @Override
    public void updateHeadImg(String token, String img) {
        Assert.isBlank(img, "img地址不能为空");
        SysAgent agent = queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        SysAgent agentInfo = new SysAgent();
        agentInfo.setAgentId(agentId);
        agentInfo.setHeadImg(img);
        baseMapper.updateAgentById(agentInfo);
    }


    @Override
    public PageUtils queryAgentList(Map<String, Object> params) {
        int currPage = Integer.valueOf(params.get("page").toString());
        int pageSize = Integer.valueOf(params.get("limit").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> list = baseMapper.queryAgentList(params);
        Long deptId = Long.valueOf(params.get("deptId").toString());
        for (Map<String, Object> map : list) {
            String thisGrade = map.get("thisGrade").toString();
            if (deptId.equals(5L)) {
                map.put("thisGrade", "M" + thisGrade);
            } else {
                map.put("thisGrade", "V" + thisGrade);
            }
        }
        int totalCount = baseMapper.queryCount(params);
        redisUtil.set("agentDown", params, 5 * 60);
        return new PageUtils(list, totalCount, pageSize, currPage);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void freezAgent(SysAgent agent) {
        this.baseMapper.freezAgent(agent);
    }

    @Override
    public Map<String, Object> findAgentDetail(Long agentId) {
        Map<String, Object> sysAgent = this.baseMapper.findAgentDetail(agentId);
        Integer locked = (Integer) sysAgent.get("locked");
        sysAgent.put("locked", locked == 1);
        return sysAgent;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAgent(Map<String, Object> params) {
        //获取原有的合伙人信息
        SysAgent agent = this.queryAgentById(Long.valueOf(params.get("agentId").toString()));
        //如果不相等，则修改
       /* if (!agent.getPassword().equals(params.get("password").toString())) {
            String MD5Password = MD5Util.generate(params.get("password").toString());
            agent.setPassword(MD5Password);
        }*/
        agent.setPhone(params.get("phone").toString());
        agent.setType(Integer.valueOf(params.get("type").toString()));
        agent.setName(params.get("name").toString());
        //修改合伙人
        this.baseMapper.updateAllColumnById(agent);
        //修改合伙人详细信息
        SysAgentInfo sysAgentInfo = new SysAgentInfo();
        sysAgentInfo.setAgentInfoId(Long.valueOf(params.get("agentInfoId").toString()));
        sysAgentInfo.setAgentId(Long.valueOf(params.get("agentId").toString()));
        sysAgentInfo.setTotalAmount(new BigDecimal(params.get("totalAmount").toString()));
        sysAgentInfo.setAvailableAmount(new BigDecimal(params.get("availableAmount").toString()));
        if (agent.getDeptId().equals(5L)) {
            sysAgentInfo.setFreeznAmount(new BigDecimal(params.get("freeznAmount").toString()));
        }
        if (params.get("idCard") != null) {
            sysAgentInfo.setIdCard(params.get("idCard").toString());
        }
        if (agent.getDeptId().equals(5L)) {
            TLTranBalance(agent, new BigDecimal(params.get("totalAmount").toString()), new BigDecimal(params.get("availableAmount").toString()),
                    new BigDecimal(params.get("freeznAmount").toString()));

        }

        agentInfoService.updateById(sysAgentInfo);

        //修改合伙人等级信息
        SysAgentGrade sysAgentGrade = agentGradeService.queryGradeByAgentId(agent.getAgentId());
        sysAgentGrade.setThisGrade(Integer.valueOf(params.get("thisGrade").toString()));
        sysAgentGrade.setAgentId(Long.valueOf(params.get("agentId").toString()));
        sysAgentGrade.setLocked((boolean) params.get("locked") ? 1 : 0);
        agentGradeService.updateById(sysAgentGrade);


    }

    private void TLTranBalance(SysAgent agent, BigDecimal totalAmount, BigDecimal availableAmount, BigDecimal freeznAmount) {
        SysAgentInfo info = agentInfoService.getAgentInfoById(agent.getAgentId());
        //冻结减少则进行处理
        if (info.getFreeznAmount().compareTo(freeznAmount) == 1) {
            BigDecimal addTotalAmount = totalAmount.subtract(info.getTotalAmount());
            BigDecimal addAvailableAmount = availableAmount.subtract(info.getAvailableAmount());

            if (addTotalAmount.compareTo(addAvailableAmount) != 0) {
                throw new RRException("9000", "总金额与可提余额增量不同");
            }
            //添加流水
            FlowAccount flowAccount = new FlowAccount();

            flowAccount.setAccountType(7);
            flowAccount.setSupportType(2);
            flowAccount.setAgentId(agent.getAgentId());
            flowAccount.setAmount(addAvailableAmount);
            flowAccount.setCreateTime(new Date());
            flowAccountService.insert(flowAccount);

        }


    }

    @Override
    public Long checkParent(String phone, String parentName, Long deptId) {
        String name = this.baseMapper.checkParent(phone, deptId);
        if (name == null) {
            throw new RRException("9000", "查无此合伙人");
        }
        if (!name.equals(parentName)) {
            throw new RRException("9000", "请填写正确的合伙人姓名");
        }
        Long agentId = baseMapper.queryAgentIdByphoneAndName(phone, parentName, deptId);
        return agentId;
    }

    @Override
    public PageUtils queryForbidAgentList(Map<String, Object> params) {
        int currPage = Integer.valueOf(params.get("page").toString());
        int pageSize = Integer.valueOf(params.get("limit").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> list = this.baseMapper.queryForbidAgentList(params);
        int totalCount = this.baseMapper.queryForbidAgentCount(params);
        return new PageUtils(list, totalCount, pageSize, currPage);
    }


    @Override
    public List<SysAgent> queryByName(String name, Long deptId) {
        return this.baseMapper.queryByName(name, deptId);
    }


    @Override
    public SysAgent queryBasicAgentBydeptId(Long deptId) {
        return baseMapper.queryBasicAgentByDeptId(deptId);
    }

    @Override
    public List<SysAgent> queryRealSubAgent(Long agentId, Integer type) {
        return baseMapper.queryRealSubAgent(agentId, type);
    }

    @Override
    public SysAgent queryTopAgentBySubIdAndBase(Long subId, Long baseAgentId) {
        return baseMapper.queryTopAgentBySubIdAndBase(subId, baseAgentId);
    }

    @Override
    public void pushDelMerNotice(TerMerchantReport report) {
        SysAgent agent = queryAgentById(report.getAgentId());
        if (agent == null) {
            return;
        }
        if (agent.getPushState().intValue() != 1) {
            return;
        }

        //找到配置信息
        PushConfig pushConfig = pushConfigService.queryPushConfigByDeptId(agent.getDeptId());
        if (pushConfig == null) {
            return;
        }
        //设置配送内容
        PushContent pushContent = new PushContent();
        pushContent.setPushType("alias");
        pushContent.setAlert("您于" + DateUtils.format(report.getCreateDate(), DateUtils.DATE_PATTERN) + "日报备的商户" + report.getMerchantName() + "无交易,已删除");
        pushContent.setTitle("商户相关");
        pushContent.setNoticeType("ass");
        pushContent.setAssType(2);
        pushContent.setAlias(new String[]{String.valueOf(report.getAgentId())});
        //推送消息
        JiGuangPush.jiguangPush(pushContent, pushConfig);
    }

    @Override
    public void updateAgentGrade(Long agentId) {
        SysAgent agent = queryAgentById(agentId);
        if (!agent.getDeptId().equals(1L)) {
            return;
        }
        SysAgentGrade agentGrade = agentGradeService.queryGradeByAgentId(agentId);
        agentGrade.setThisGrade(5);
        agentGrade.setUpdateTime(new Date());
        agentGrade.setLocked(1);
        agentGradeService.updateById(agentGrade);
    }

    @Override
    public Map<String, Object> registStarpos(RegistStarposBean bean, String token) {
        SysAgent agent = queryAgentByToken(token);
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("success", true);
        returnMap.put("msg", "进件成功,请等待图片上传");
        if (
                bean.getMercNm() == null || "".equals(bean.getMercNm()) ||
                        bean.getMercNm() == null || "".equals(bean.getMercNm()) ||
                        bean.getStoe_adds() == null || "".equals(bean.getStoe_adds()) ||
                        bean.getStoe_cnt_tel() == null || "".equals(bean.getStoe_cnt_tel()) ||
                        bean.getMcc_cd() == null || "".equals(bean.getMcc_cd()) ||
                        bean.getTrm_scan() == null || "".equals(bean.getTrm_scan()) ||
                        bean.getBnk_acnm() == null || "".equals(bean.getBnk_acnm()) ||
                        bean.getStl_oac() == null || "".equals(bean.getStl_oac()) ||
                        bean.getWc_lbnk_no() == null || "".equals(bean.getWc_lbnk_no()) ||
                        bean.getProv() == null || "".equals(bean.getProv()) ||
                        bean.getCity() == null || "".equals(bean.getCity()) ||
                        bean.getArea() == null || "".equals(bean.getArea()) ||
                        bean.getCrp_exp_dt_tmp() == null || "".equals(bean.getCrp_exp_dt_tmp()) ||
                        bean.getIcrp_id_no() == null || "".equals(bean.getIcrp_id_no())
        ) {
            throw new RRException("9000", "请补全进件资料！");
        }
        //签名信息
        CustomerSignInfo info = new CustomerSignInfo();
        String mccresult = StarposVerify.stoecode(bean.getProv(), bean.getCity());
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(mccresult, Map.class);
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("REC");
        for (Map<String, Object> objectMap : list) {
            String area = objectMap.get("area_nm").toString();
            if (area.equals(bean.getArea())) {
                //地区码
                info.setStoe_area_cod(objectMap.get("merc_area").toString());
                break;
            }
        }

        //邮箱
        info.setMailbox("17798509319@163.com");
        //开户行行号
        info.setWc_lbnk_no(bean.getWc_lbnk_no());
        //版本
        info.setVersion("V1.0.5");
        //联系方式
        info.setStoe_cnt_tel(bean.getStoe_cnt_tel());
        //联系人名称
        info.setStoe_cnt_nm(bean.getBnk_acnm());
        //详细地址
        info.setStoe_adds(bean.getStoe_adds());
        //结算类型
        info.setStl_typ("1");
        //结算地址
        info.setStl_oac(bean.getStl_oac());
        //签购单名称 省市+商户经营名称
        String stoeNm = bean.getMercNm();
        ;
        //不包含市则拼接市
        if (!stoeNm.contains(bean.getCity())) {
            stoeNm = bean.getCity() + stoeNm;
        }
        //不包含省则拼接省
        if (!stoeNm.contains(bean.getProv())) {
            stoeNm = bean.getProv() + stoeNm;
        }

        info.setStoe_nm(stoeNm);
        //扫码
        info.setAlipay_flg("Y");
        info.setYhkpay_flg("N");
        //结算标志
        info.setStl_sign("1");
        //区域码
        info.setMcc_cd(bean.getMcc_cd());
        //结算类型
        info.setIncom_type("3");
        //户名
        info.setBnk_acnm(bean.getBnk_acnm());

        //无需签名的字段
        CustomerUnsignBean unsignBean = new CustomerUnsignBean();

        //法人
        //unsignBean.setCrp_id_no(bean.getCrp_id_no());
        //unsignBean.setCrp_exp_dt(bean.getCrp_exp_dt());

        //商户经营名称
        unsignBean.setMercNm(bean.getMercNm());
        //结算人身份证信息
        unsignBean.setCrp_exp_dt_tmp(bean.getCrp_exp_dt_tmp());
        unsignBean.setIcrp_id_no(bean.getIcrp_id_no());
        //扫码费率
        unsignBean.setFee_rat3_scan("0.38");
        unsignBean.setFee_rat_scan("0.38");

        unsignBean.setTrm_tp(bean.getTrm_scan());
        String result = CustomerQuickRegist.customerQuickRegist(info, unsignBean);
        Map<String, Object> resultMap = gson.fromJson(result, Map.class);
        String msgCd = resultMap.get("msg_cd").toString();
        String mercId;
        String stoe_id;
        String log_no;
        if ("000000".equals(msgCd)) {

            mercId = resultMap.get("mercId").toString();
            stoe_id = resultMap.get("stoe_id").toString();
            log_no = resultMap.get("log_no").toString();
            returnMap.put("mercId", mercId);


        } else {
            throw new RRException("9000", resultMap.get("msg_dat").toString());
        }

        StarposMercInfo starposMercInfo = new StarposMercInfo();
        String no = StringUtil.getDateString(6);
        starposMercInfo.setCustomerNo(no);
        starposMercInfo.setBnkAcnm(bean.getBnk_acnm());
        starposMercInfo.setLogNo(log_no);
        starposMercInfo.setMccCd(bean.getMcc_cd());
        starposMercInfo.setMercAddress(stoeNm);
        starposMercInfo.setMercId(mercId);
        starposMercInfo.setMercNm(bean.getMercNm());
        starposMercInfo.setStlOac(bean.getStl_oac());
        starposMercInfo.setStoeAdds(bean.getStoe_adds());
        starposMercInfo.setStoeAreaCod(info.getStoe_area_cod());
        starposMercInfo.setStoeCntTel(bean.getStoe_cnt_tel());
        starposMercInfo.setStoeId(stoe_id);
        starposMercInfo.setTrmScan(bean.getTrm_scan());
        starposMercInfo.setWcLbnkNo(bean.getWc_lbnk_no());
        starposMercInfo.setAgentId(agent.getAgentId());

        starposMercInfoService.insert(starposMercInfo);

        return returnMap;
    }

    @Override
    public Map<String, Object> uploadStarPosImg(String mercId, String url1, String url2, String url3) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("msg", "上传成功,请等待审核");
        StarposMercInfo info = starposMercInfoService.queryByMercId(mercId);
        Gson gson = new Gson();


        CustomerImgUploadBean uploadBean = new CustomerImgUploadBean();
        uploadBean.setMercId(mercId);
        uploadBean.setStoe_id(info.getStoeId());
        uploadBean.setLog_no(info.getLogNo());
        uploadBean.setVersion("V1.0.1");
        //url1 身份证正面
        String filepath1 = url1.substring(url1.indexOf("data:image/") + 11, url1.indexOf(";base64,"));
        uploadBean.setImgTyp("9");
        uploadBean.setImgNm("identityFront." + filepath1);
        String base64Str = url1.replace("data:image/" + filepath1 + ";base64,", "");
        base64Str = base64Str.replace(" ", "+");
        System.out.println("身份证正面" + base64Str);
        byte[] enc641 = Base64Utils.decode(base64Str);

        String imgStr1 = ByteUtil.byteArrayToHexStr(enc641);

        String imgResult = CustomerImgUpload.upload(uploadBean, imgStr1);
        Map<String, Object> resultMapimg = gson.fromJson(imgResult, Map.class);
        String imgUploadcode = resultMapimg.get("msg_cd").toString();

        if (!"000000".equals(imgUploadcode)) {

            resultMap.put("code", "9000");
            resultMap.put("msg", "身份证正面上传失败");


        }


        uploadBean.setImgTyp("4");
        uploadBean.setImgNm("identityFront1." + filepath1);
        String base64Str4 = url1.replace("data:image/" + filepath1 + ";base64,", "");
        base64Str4 = base64Str4.replace(" ", "+");
        System.out.println("身份证正面" + base64Str);
        byte[] enc6414 = Base64Utils.decode(base64Str4);

        String imgStr14 = ByteUtil.byteArrayToHexStr(enc6414);

        String imgResult4 = CustomerImgUpload.upload(uploadBean, imgStr14);
        Map<String, Object> resultMapimg4 = gson.fromJson(imgResult4, Map.class);
        String imgUploadcode4 = resultMapimg4.get("msg_cd").toString();

        if (!"000000".equals(imgUploadcode4)) {

            resultMap.put("code", "9000");
            resultMap.put("msg", "身份证正面上传失败");


        }

        CustomerImgUploadBean uploadBean2 = new CustomerImgUploadBean();
        uploadBean2.setMercId(mercId);
        uploadBean2.setStoe_id(info.getStoeId());
        uploadBean2.setLog_no(info.getLogNo());
        uploadBean2.setVersion("V1.0.1");
        //url2 身份证正面
        String filepath2 = url1.substring(url2.indexOf("data:image/") + 11, url2.indexOf(";base64,"));

        //url2 身份证反面
        uploadBean2.setImgTyp("10");
        uploadBean2.setImgNm("identityBehind." + filepath2);
        String base64Str2 = url2.replace("data:image/" + filepath2 + ";base64,", "");
        System.out.println("身份证反面卡" + base64Str2);
        base64Str2 = base64Str2.replace(" ", "+");
        byte[] enc642 = Base64Utils.decode(base64Str2);

        String imgStr2 = ByteUtil.byteArrayToHexStr(enc642);

        String imgResult2 = CustomerImgUpload.upload(uploadBean2, imgStr2);
        Map<String, Object> resultMapimg2 = gson.fromJson(imgResult2, Map.class);
        String imgUploadcode2 = resultMapimg2.get("msg_cd").toString();

        if (!"000000".equals(imgUploadcode2)) {

            resultMap.put("code", "9000");

            resultMap.put("msg", "身份证反面上传失败");


        }


        //url2 身份证反面
        uploadBean2.setImgTyp("5");
        uploadBean2.setImgNm("identityBehind." + filepath2);
        String base64Str25 = url2.replace("data:image/" + filepath2 + ";base64,", "");
        System.out.println("身份证反面卡" + base64Str2);
        base64Str25 = base64Str25.replace(" ", "+");
        byte[] enc6425 = Base64Utils.decode(base64Str25);

        String imgStr25 = ByteUtil.byteArrayToHexStr(enc6425);

        String imgResult25 = CustomerImgUpload.upload(uploadBean2, imgStr25);
        Map<String, Object> resultMapimg25 = gson.fromJson(imgResult25, Map.class);
        String imgUploadcode25 = resultMapimg25.get("msg_cd").toString();

        if (!"000000".equals(imgUploadcode25)) {

            resultMap.put("code", "9000");

            resultMap.put("msg", "身份证反面上传失败");


        }


        CustomerImgUploadBean uploadBean3 = new CustomerImgUploadBean();
        uploadBean3.setMercId(mercId);
        uploadBean3.setStoe_id(info.getStoeId());
        uploadBean3.setLog_no(info.getLogNo());
        uploadBean3.setVersion("V1.0.1");
        //url3 银行卡
        String filepath3 = url1.substring(url3.indexOf("data:image/") + 11, url3.indexOf(";base64,"));

        //url3 银行卡

        uploadBean3.setImgTyp("11");
        uploadBean3.setImgNm("last." + filepath3);
        String base64Str3 = url3.replace("data:image/" + filepath3 + ";base64,", "");
        System.out.println("银行卡" + base64Str3);
        base64Str3 = base64Str3.replace(" ", "+");

        System.out.println(base64Str3);
        byte[] enc643 = Base64Utils.decode(base64Str3);

        String imgStr3 = ByteUtil.byteArrayToHexStr(enc643);

        String imgResult3 = CustomerImgUpload.upload(uploadBean3, imgStr3);
        Map<String, Object> resultMapimg3 = gson.fromJson(imgResult3, Map.class);
        String imgUploadcode3 = resultMapimg3.get("msg_cd").toString();

        if (!"000000".equals(imgUploadcode3)) {

            resultMap.put("code", "9000");

            resultMap.put("msg", "银行卡上传失败");


        }

        String str = StarposVerify.sendVerify(mercId, info.getLogNo());
        Map<String, Object> resultVer = gson.fromJson(str, Map.class);
        String resultVerCode = resultVer.get("msg_cd").toString();
        if ("000000".equals(resultVerCode)) {
            String checkFlag = resultVer.get("check_flag").toString();
            String msg;
            if ("1".equals(checkFlag)) {
                resultMap.put("msg", "审核成功");
                msg = "您的商户于" + DateUtils.format(new Date(), DateUtils.DATE_PATTERN) + "日在百易管家平台进行星POS进件成功，商户号是" + mercId + "门店号是：" + info.getStoeId();
            } else if ("2".equals(checkFlag)) {
                resultMap.put("msg", "审核失败，" + resultVer.get("check_msg").toString());
                msg = "您的商户于" + DateUtils.format(new Date(), DateUtils.DATE_PATTERN) + "日在百易管家平台进行星POS进件审核失败," + resultVer.get("check_msg");
            } else {
                resultMap.put("msg", "已发送至人工审核");
                msg = "您的商户于" + DateUtils.format(new Date(), DateUtils.DATE_PATTERN) + "日在百易管家平台进行星POS进件转入人工审核,";
            }

            String mess = deptSmsService.sendCusRegResult(info, msg);
            resultMap.put("msg", mess);

        } else {
            resultMap.put("code", "9000");
            resultMap.put("msg", resultVer.get("msg_dat").toString());
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> getRateList(Long agentId, Long deptId) {
        return agentGradeService.getRateList(agentId, deptId);
    }

    @Override
    public void updateIdentity(String token, String identity, String smsCode) {
        SysAgent sysAgent = queryAgentByToken(token);
        //检查验证码
        String value = deptSmsService.checkSms(SmsType.UPDATE_IDENTITY.getValue(), sysAgent.getPhone(), smsCode);

        SysAgentInfo agentInfo = agentInfoService.selectOne(new EntityWrapper<SysAgentInfo>().eq("agent_id", sysAgent.getAgentId()));
        if (agentInfo == null) {
            throw new RRException("9000", "未查询到详细信息");
        }
        agentInfo.setIdCard(identity);
        agentInfoService.updateById(agentInfo);

        redisUtil.del(value);
    }

    @Override
    public void updateBank(String token, String bankName, String smsCode, String bankCode, String phone) {

        Assert.isBlank(bankName, "银行名称不能为空");
        Assert.isBlank(bankCode, "银行卡号码不能为空");

        bankCode = Assert.hasSpace(bankCode);
        bankName = Assert.hasSpace(bankName);
        if ((!bankName.contains("行")) && (!bankName.contains("银"))) {
            throw new RRException("9000", "请输入正确的银行名称");
        }

        SysAgent sysAgent = queryAgentByToken(token);
        //检查验证码
        deptSmsService.checkSms(SmsType.UPDATE_BANK.getValue(), sysAgent.getPhone(), smsCode);
        SysPayment sysPayment = paymentService.queryPaymentByDeptId(sysAgent.getDeptId());

        boolean yfFlag = sysPayment.getPayType().intValue() == 5;

        if (yfFlag) {
            Assert.isBlank(phone, "请填写预留手机号码");
        }

        SysBank sysBank = bankService.selectOne(new EntityWrapper<SysBank>()
                .eq("agent_id", sysAgent.getAgentId())
                .eq("is_default", 1)
        );
        Integer logoId = sysBankLogoService.returnLogoIdByBankName(bankName);

        if (sysBank == null) {
            sysBank = new SysBank();
            sysBank.setDeptId(sysAgent.getDeptId());
            sysBank.setBankName(bankName);
            sysBank.setBankNo(bankCode);
            sysBank.setAgentId(sysAgent.getAgentId());
            sysBank.setBankLogoId(logoId);
            sysBank.setCardName(sysAgent.getName());
            sysBank.setIsShow(1);
            sysBank.setPhone(yfFlag ? phone : sysAgent.getPhone());
            bankService.insert(sysBank);

        } else {
            sysBank.setCardName(sysAgent.getName());
            sysBank.setBankName(bankName);
            sysBank.setBankNo(bankCode);
            sysBank.setBankLogoId(logoId);
            sysBank.setIsShow(1);
            sysBank.setPhone(yfFlag ? phone : sysAgent.getPhone());
            bankService.updateById(sysBank);
        }
    }

    @Override
    public void updatePhone(String token, String newPhone, String smsCode) {
        SysAgent sysAgent = queryAgentByToken(token);
        Assert.isBlank(newPhone, "新账号不能为空");
        if (newPhone.equals(sysAgent.getPhone())) {
            throw new RRException("9000", "请不要输入当前帐号");

        }
        deptSmsService.checkSms(SmsType.UPDATE_PHONE.getValue(), newPhone, smsCode);

        SysAgent agent = queryByMobileAndDeptId(newPhone, sysAgent.getDeptId());
        if (agent != null) {
            throw new RRException("9000", "此账号:" + newPhone + "已被注册");
        }
        sysAgent.setPhone(newPhone);
        baseMapper.updateById(sysAgent);
        String str = (String) redisUtil.get(token);
        redisUtil.set(str, sysAgent, 0);

    }

    @Override
    public void updateName(String token, String newName, String smsCode) {
        SysAgent sysAgent = queryAgentByToken(token);
        Assert.isBlank(newName, "新姓名不能为空");
        deptSmsService.checkSms(SmsType.UPDATE_NAME.getValue(), sysAgent.getPhone(), smsCode);

        sysAgent.setName(newName);
        baseMapper.updateById(sysAgent);
        String str = (String) redisUtil.get(token);
        redisUtil.set(str, sysAgent, 0);
    }

    @Override
    public Map<String, Object> getInfoByToken(String token) {
        Map<String, Object> result = new HashMap<>(4);
        SysAgent sysAgent = queryAgentByToken(token);

        sysAgent = baseMapper.selectById(sysAgent.getAgentId());
        SysBank bank = bankService.selectOne(new EntityWrapper<SysBank>()
                .eq("agent_id", sysAgent.getAgentId())
                .eq("is_show", 1)
                .eq("is_default", 1));
        Map<String, Object> map = new HashMap<>(4);

        if (bank != null) {
            map.put("bankNo", bank.getBankNo());
            map.put("bankName", bank.getBankName());
            SysPayment sysPayment = paymentService.queryPaymentByDeptId(sysAgent.getDeptId());
            if (sysPayment.getPayType().intValue() == 5) {
                map.put("reservedPhone", bank.getPhone());
            }
        }
        map.put("realName", sysAgent.getRealName());

        SysAgentInfo info = agentInfoService.getAgentInfoById(sysAgent.getAgentId());
        map.put("idCard", info.getIdCard() == null ? "" : info.getIdCard());

        SysAgentGrade agentGrade = agentGradeService.selectOne(new EntityWrapper<SysAgentGrade>().eq("agent_id", sysAgent.getAgentId()));

        sysAgent.setThisGrade(agentGrade.getThisGrade());

        result.put("realInfo", map);
        result.put("sysAgent", sysAgent);

        return result;
    }

    @Override
    public void updatePassword(String token, String password, String confPassword, String smsCode, String oldPassword) {
        SysAgent agent = queryAgentByToken(token);
        Assert.isBlank(oldPassword, "原始密码不能为空");
        Assert.isBlank(password, "新密码不能为空");
        Assert.isBlank(confPassword, "确认密码不能为空");
        Assert.isBlank(smsCode, "验证码不能为空");

        String value = deptSmsService.checkSms(SmsType.UPDATE_PASSWORD.getValue(), agent.getPhone(), smsCode);

        //AES解密
        String oldResult = AesUtil.aesDecrypt(oldPassword);
        Assert.isBlank(oldResult, "解密错误");
        String oldpwd = MD5Util.string2MD5(oldResult);
        if (!oldpwd.equals(agent.getPassword())) {
            throw new RRException("9000", "原始密码错误");
        }
        if (!password.equals(confPassword)) {
            throw new RRException("9000", "新密码与确认密码不同");
        }
        //AES解密
        String textPassword = AesUtil.aesDecrypt(password);
        Assert.isBlank(textPassword, "加密错误");
        //MD5加盐加密
        String MD5Password = MD5Util.string2MD5(textPassword);
        agent.setPassword(MD5Password);
        baseMapper.updateAgentById(agent);

        redisUtil.del(value);
    }

    @Override
    public Map<String, Object> getWalletInfo(String token) {
        Map<String, Object> result = new HashMap<>(3);
        SysAgent agent = queryAgentByToken(token);
        SysAgentInfo info = agentInfoService.getAgentInfoById(agent.getAgentId());
        result.put("amount", info.getAvailableAmount());

        List<FlowTask> flowTasks = flowTaskService.selectList(new EntityWrapper<FlowTask>()
                .eq("agent_id", agent.getAgentId())
                .eq("task_state", "success")
        );
        BigDecimal takeAmount = flowTasks.stream().map(FlowTask::getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

        result.put("takeAmount", takeAmount);

        List<Map<String, Object>> tableAccount = flowAccountService.queryFlowAccountTable(token, 1, null, null);
        result.put("tableAccount", tableAccount);
        return result;
    }

    @Override
    public void updateTradePassword(String token, String password, String confPassword, String smsCode, String oldPassword) {
        SysAgent agent = queryAgentByToken(token);
        if (!"1".equals(agent.getRealName())) {
            throw new RRException("9000", "请先实名认证");
        }
        SysAgentInfo info = agentInfoService.getAgentInfoById(agent.getAgentId());
        Assert.isBlank(oldPassword, "原始交易密码不能为空");
        Assert.isBlank(password, "新交易密码不能为空");
        Assert.isBlank(confPassword, "确认密码不能为空");
        Assert.isBlank(smsCode, "验证码不能为空");

        String value = deptSmsService.checkSms(SmsType.UPDATE_TRADEPASSWORD.getValue(), agent.getPhone(), smsCode);

        //AES解密
        String oldResult = AesUtil.aesDecrypt(oldPassword);
        Assert.isBlank(oldResult, "解密错误");
        String oldpwd = MD5Util.string2MD5(oldResult);

        if (!oldpwd.equals(info.getTakePassword())) {
            throw new RRException("9000", "原始交易密码错误");
        }
        if (!password.equals(confPassword)) {
            throw new RRException("9000", "新密码与确认密码不同");
        }
        //AES解密
        String textPassword = AesUtil.aesDecrypt(password);
        Assert.isBlank(textPassword, "加密错误");
        //MD5加盐加密
        String MD5Password = MD5Util.string2MD5(textPassword);

        info.setTakePassword(MD5Password);

        agentInfoService.updateById(info);
        redisUtil.del(value);
    }

    @Override
    public void generateQR(String token) {
        SysAgent sysAgent = queryAgentByToken(token);
        String s = QRCodeUtils.generateQRAndUpload("1231244", 200, 200, sysAgent.getAgentId().toString());
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(sysAgent.getAgentId());
        agentInfo.setRegisterQrImg(s);
        agentInfoService.updateById(agentInfo);
    }

    @Override
    public void cancelRealName(Long agentId) {
        SysAgent sysAgent = queryAgentById(agentId);
        sysAgent.setRealName("0");
        bankService.delete(new EntityWrapper<SysBank>().eq("agent_id", sysAgent.getAgentId()));
        baseMapper.updateById(sysAgent);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void realNameByAdmin(Map<String, Object> params, Long deptId) {
        Long agentId = Long.valueOf(params.get("agentId").toString());
        String identity = params.get("identity").toString();
        String bankNo = params.get("bankNo").toString();
        String bankName = params.get("bankName").toString();

        SysAgent sysAgent = queryAgentById(agentId);
        if (sysAgent == null) {
            throw new RRException("9000", "未查询到该合伙人:" + agentId);
        }


        sysAgent.setRealName("1");
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agentId);

        if (agentInfo == null) {
            throw new RRException("9000", "未查询到该合伙人信息:" + agentId);
        }
        agentInfo.setIdCard(identity);
        agentInfoService.updateById(agentInfo);

        SysBank bank = bankService.selectBankByNo(bankNo, deptId);
        if (bank != null) {
            throw new RRException("9000", "该银行卡号已用于实名");
        }


        SysBank sysBank = bankService.selectOne(new EntityWrapper<SysBank>()
                .eq("agent_id", sysAgent.getAgentId())
                .eq("is_default", 1)
        );

        Integer logoId = sysBankLogoService.returnLogoIdByBankName(bankName);

        if (sysBank == null) {
            sysBank = new SysBank();
            sysBank.setCardName(sysAgent.getName());
            sysBank.setDeptId(sysAgent.getDeptId());
            sysBank.setBankName(bankName);
            sysBank.setBankNo(bankNo);
            sysBank.setAgentId(sysAgent.getAgentId());
            sysBank.setBankLogoId(logoId);
            sysBank.setCreateDate(new Date());
            bankService.insert(sysBank);

        } else {
            sysBank.setBankName(bankName);
            sysBank.setBankNo(bankNo);
            sysBank.setBankLogoId(logoId);
            sysBank.setCardName(sysAgent.getName());
            bankService.updateById(sysBank);
        }

        updateById(sysAgent);

    }


    @Override
    public Map<String, Object> takeIndexInfo(String token) {

        Map<String, Object> map = new HashedMap();

        SysAgent agent = queryAgentByToken(token);

        SysAgent sysAgent = queryAgentById(agent.getAgentId());

        if (sysAgent.getState().intValue() == 3) {
            if (sysAgent.getDeptId().equals(889323L)) {
                throw new RRException("9000", "提现休眠状态，请联系客服");
            } else {
                throw new RRException("9000", "提现暂被封禁,请联系客服");
            }

        }
        Map<String, Object> amountInfo = new HashMap<>(3);
        Long deptId = agent.getDeptId();
        Long agentId = agent.getAgentId();
        //默认银行卡信息
        SysBank bank = bankService.queryDefault(agentId);
        if (bank == null) {
            throw new RRException("9000", "未查询到银行卡");

        }
        if (bank.getBankLogoId() == null) {
            bank = sysBankLogoService.setBankLogoId(bank);
        }
        bank.setBankLogoUrl(sysBankLogoService.selectById(bank.getBankLogoId()).getLogoUrl());
        map.put("bank", bank);
        //可提余额
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agentId);
        amountInfo.put("amount", MathUtils.formatToNumber(agentInfo.getAvailableAmount()));
        //手续费率
        SysPayment payment = paymentService.queryPaymentByDeptId(deptId);
        if (payment == null) {
            throw new RRException("9000", "未查询到代付配置信息");
        }
        if (payment.getState().intValue() == 2) {
            throw new RRException("9000", payment.getRemark());
        }
        amountInfo.put("minAmount", payment.getMinAmount());
        amountInfo.put("chargeAmount", payment.getChargeAmount());
        amountInfo.put("chargeRate", payment.getChargeRate() + "%");
        map.put("amountInfo", amountInfo);
        //通联添加冻结相关内容
        if (deptId.equals(5L)) {
            FlowFrozenTerminal flowFrozenTerminal = flowFrozenTerminalService.selectOne(
                    new EntityWrapper<FlowFrozenTerminal>().eq("agent_id", agentId).eq("state", 0));
            map.put("frozenAmount", flowFrozenTerminal == null ? "0.00" : MathUtils.formatToNumber(flowFrozenTerminal.getAmount()));
        }

        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void verifiedAgent(NewAgentVerifiedForm form, String token) {
        // 表单校验
        ValidatorUtils.validateEntity(form);
        String phone = form.getPhone();
        String name = form.getName();
        String idCard = form.getIdCard();
        String password = form.getPassword();
        String bankNo = form.getBankNo();

        String vCode = form.getVCode();
        //身份证验证
        //Verified.verfiedIDCard(name, idCard);

        //根据token查询代理商缓存
        SysAgent sysAgent = queryAgentByToken(token);
        if (!name.equals(sysAgent.getName())) {
            throw new RRException("9000", "注册名和身份证名不同!");
        }
        Assert.isBlank(password, "请输入交易密码");

        Long agentId = sysAgent.getAgentId();
        Long deptId = sysAgent.getDeptId();
        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agentId);
        //判断是否实名认证
        SysAgent agent = queryAgentById(agentId);
        String realName = agent.getRealName();
        if (StringUtils.equals("1", realName)) {
            throw new RRException("9000", "已经完成实名认证");
        }
        //校验卡号是否存在
        SysBank sysBank = bankService.selectBankByNo(bankNo, deptId);
        if (sysBank != null) {
            throw new RRException("9000", "银行卡号已经存在");
        }

        //校验实名认证验证码
        String value = deptSmsService.checkSms("i_bank", agent.getPhone(), vCode);
        SysPayment sysPayment = paymentService.queryPaymentByDeptId(deptId);
        //添加银行卡
        SysBank bank = null;
        if (sysPayment.getPayType().intValue() == 5) {
            bank = bankService.addBankByVerify(bankNo, agent, phone);
        } else {
            bankService.addBankByVerify(bankNo, agent);
        }

        //修改认证信息
        agentInfo.setIdCard(idCard);
        //获取交易密码
        String result = AesUtil.aesDecrypt(password);
        Assert.isBlank(result, "解密错误");
        String curPwd = MD5Util.string2MD5(result);

        agentInfo.setTakePassword(curPwd);
        if (sysPayment.getPayType().intValue() == 5) {
            agentInfo.setIdCardBackImg(form.getIdentityHead());
            agentInfo.setIdCardFrontImg(form.getIdentityEm());
        }
        agentInfoService.updateAgentInfoById(agentInfo);

        agent.setRealName("1");
        updateAgentById(agent);
        //覆盖用户缓存
        redisUtil.set(agent.getPhone() + "," + agent.getDeptId(), agent, 0);

        //代付类型为5:优付代付的 需要签约
        if (sysPayment.getPayType().intValue() == 5) {
            Assert.isBlank(form.getIdentityHead(), "身份证头像面不能为空");
            Assert.isBlank(form.getIdentityEm(), "身份证国徽面不能为空");
            signContract(form.getPhone(), form.getIdentityHead(), form.getIdentityEm(), agent, bank);
        }

        //去除验证码的缓存
        redisUtil.del(value);
    }

    @Override
    public List<String> shareByToken(String token, Integer shareId) {
        SysAgent agent = queryAgentByToken(token);
        List<SysShareImg> shareImgs = sysShareImgServcie.selectList(new EntityWrapper<SysShareImg>().eq("share_id", shareId));
        if (shareImgs.size() <= 0) {
            throw new RRException("9000", "该文案没有图片");
        }
        SysAgentInfo info = agentInfoService.getAgentInfoById(agent.getAgentId());
        String shareQrName = info.getRegisterQrImg();
        Assert.isBlank(shareQrName, "请先生成二维码");

        List<String> list = new ArrayList<>();
        String aliUrl = "https://mpos-img.oss-cn-beijing.aliyuncs.com/";
        try {
            String path = ResourceUtils.getURL("classpath:").getPath();
            String rootPath = path + "upload/";
            File file = new File(rootPath);
            if (!file.exists()) {
                file.mkdir();
            }
            String qrUrl = rootPath + shareQrName.substring(shareQrName.lastIndexOf("/") + 1);
            AliOssUtils.downloadToFile(shareQrName, qrUrl);
            System.out.println(qrUrl);
            for (SysShareImg e : shareImgs) {
                String imgUrl = e.getImgUrl();
                String baseObjectName = imgUrl.substring(imgUrl.indexOf("com/") + 4);
                String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
                String baseUrl = rootPath + fileName;
                System.out.println(baseUrl);
                AliOssUtils.downloadToFile(baseObjectName, baseUrl);
                String resultUrl = rootPath + e.getImgId() + agent.getAgentId() + ".jpg";
                String resultName = "share/" + e.getImgId() + agent.getAgentId() + ".jpg";
                ImgCoverUtils.bigImgAddSmallImg(baseUrl, qrUrl, 300, 300, resultUrl);
                AliOssUtils.uploadByPath(resultUrl, resultName);
                list.add(aliUrl + resultName);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Map<String, Object> getCusService(String token) {
        SysAgent sysAgent = queryAgentByToken(token);
        SysAgent baseAgent = queryBasicAgentBydeptId(sysAgent.getDeptId());
        SysAgent pAgent;
        if (baseAgent.getAgentId().equals(sysAgent.getAgentId())) {
            pAgent = baseAgent;
        } else {

            pAgent = queryAgentById(sysAgent.getPid());
        }

        Map<String, Object> result = new HashMap<>(3);

        result.put("name", pAgent.getName());
        result.put("headImg", pAgent.getHeadImg() == null ? "" : pAgent.getHeadImg());
        result.put("phone", pAgent.getPhone());

        return result;
    }

    @Override
    public void setPushState(String token, Integer state) {
        if (state == null) {
            throw new RRException("9000", "推送状态不能为空");
        }
        SysAgent agent = queryAgentByToken(token);
        agent.setPushState(state);
        updateById(agent);
    }

    @Override
    public void addYhbActivAmount(String sn, BigDecimal reapAmount) {
        Long own = distribuService.queryTerminalOwn(sn);
        SysAgent agent = queryAgentById(own);

        TerTerminalInfo terminalInfo = terminalInfoService.queryTerminalBySn(sn);

        terminalInfo.setIsActivation(2);
        terminalInfo.setActivationDate(new Date());
        terminalInfoService.updateById(terminalInfo);
        if (terminalInfo.getIsOnLine().intValue() == 1) {
            agentInfoService.addAmount(agent.getAgentId(), reapAmount);

            FlowActiv flowActiv = new FlowActiv();
            flowActiv.setAmount(reapAmount);
            flowActiv.setAgentId(agent.getAgentId());
            flowActiv.setSn(sn);
            flowActiv.setActivDate(new Date());
            flowActiv.setPartAmount(reapAmount);
            flowActiv.setCreateTime(new Date());
            String id = StringUtil.getDateString(3);
            flowActiv.setActivId(id);
            flowActivService.insert(flowActiv);

            FlowAccount flowAccount = new FlowAccount();

            flowAccount.setAmount(reapAmount);
            flowAccount.setSupportType(2);
            flowAccount.setAccountType(5);
            flowAccount.setBelId(id);
            flowAccount.setAgentId(agent.getAgentId());
            flowAccount.setCreateTime(new Date());
            flowAccount.setProfit(reapAmount);

            flowAccountService.insert(flowAccount);
        }


    }

    @Override
    public void cleanImg(String token, String[] imgUrl) {
        SysAgent agent = queryAgentByToken(token);
        SysAgentInfo info = agentInfoService.getAgentInfoById(agent.getAgentId());
        String shareQrName = info.getRegisterQrImg();

        try {
            String path = ResourceUtils.getURL("classpath:").getPath();
            String rootPath = path + "upload/";
            File file;
            String qrUrl = rootPath + shareQrName.substring(shareQrName.lastIndexOf("/") + 1);
            file = new File(qrUrl);
            if (file.exists()) {
                file.delete();
            }

            for (String s : imgUrl) {
                file = new File(s);
                if (file.exists()) {
                    file.delete();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public Map<String, Object> queryPartnerInfo(String token, String partnerCount, String thisMonthAmount, String merchantCount, String realName, String name, String thisMonthActiv) {
        Map<String, Object> map = new HashedMap();
        SysAgent agent = queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //直属合伙人列表
        if (realName.contains("认证")) {
            realName = "已认证".equals(realName) ? "1" : "0";
        }
        List<PartnerView> list = baseMapper.querySubAgentList(agentId, partnerCount, thisMonthAmount, merchantCount, realName, name, thisMonthActiv);
        //合伙人统计数据
        map.put("list", list);
        map.put("allCount", list.size());
        return map;
    }

    @Override
    public SysAgent queryAgentByNameAndPhone(String name, String phone) {
        return selectOne(new EntityWrapper<SysAgent>().eq("name", name).eq("phone", phone));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void signContractByToken(String token, String phone, String identityHead, String identityEm, String vCode) {
        SysAgent agent = queryAgentByToken(token);

        String value = deptSmsService.checkSms("i_bank", agent.getPhone(), vCode);

        Assert.isBlank(phone, "请输入预留手机号码");
        //校验实名认证验证码
        signContract(phone, identityHead, identityEm, agent, null);
        //去除验证码的缓存
        redisUtil.del(value);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void signContract(String phone, String identityHead, String identityEm, SysAgent agent, SysBank sysBank) {
        sysBank = sysBank == null ? bankService.queryBankByAgentId(agent.getAgentId()) : sysBank;

        Assert.isNull(sysBank, "未查询到银行卡");

        SysAgentInfo agentInfo = agentInfoService.getAgentInfoById(agent.getAgentId());

        Assert.isNull(agentInfo, "未查询到个人详细信息");

        SysDict secretKey = dictService.querySysDict(agent.getDeptId().intValue(), "1", "pay_secret_key");
        SysDict levyId = dictService.querySysDict(agent.getDeptId().intValue(), "1", "pay_lay_id");
        SysPayment payment = paymentService.queryPaymentByDeptId(agent.getDeptId());

        sysBank.setPhone(phone);
        sysBank.setIsReserved(2);
        if (sysBank.getReservedBankNo() == null || sysBank.getReservedBankNo().length() == 0) {
            sysBank.setReservedBankNo(sysBank.getBankNo());
        }
        bankService.updateById(sysBank);

        SignContractMethod.signContract(secretKey.getValue(), payment, sysBank, agentInfo.getIdCard(), identityHead, identityEm, levyId.getValue());

    }

    @Override
    public void downLoad(Long deptId, HttpServletResponse response) {
        Map<String, Object> params;
        if (redisUtil.hasKey("agentDown")) {
            params = (Map<String, Object>) redisUtil.get("agentDown");
            params.remove("limit");
            params.remove("start");
        } else {
            params = new HashMap<>(1);
            params.put("deptId", deptId);
        }

        List<Map<String, Object>> list = baseMapper.queryAgentList(params);

        String fileName = "合伙人信息表" + System.currentTimeMillis() + ".xlsx";
        String[] title = {"推荐码", "渠道名称", "合伙人姓名", "角色", "手机号码", "推荐人", "推荐人号码", "总分润", "余额", "冻结金额", "上月激活", "vip等级", "账号状态", "验证状态", "注册时间"};
        String sheetName = "终端信息表";

        String[][] content = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Map<String, Object> obj = list.get(i);
            //推荐码
            content[i][0] = obj.get("agentId").toString();
            //渠道名称
            content[i][1] = obj.get("deptName").toString();
            //姓名
            content[i][2] = obj.get("name").toString();
            //身份
            content[i][3] = Integer.valueOf(obj.get("type").toString()).intValue() == 3 ? "盟主" : "普通";
            //手机号
            content[i][4] = obj.get("phone").toString();
            //推荐人姓名
            content[i][5] = obj.get("parentName") == null ? "无" : obj.get("parentName").toString();
            //推荐人手机
            content[i][6] = obj.get("parentPhone") == null ? "无" : obj.get("parentPhone").toString();
            //总余额
            content[i][7] = obj.get("totalAmount").toString();
            content[i][8] = obj.get("availableAmount").toString();
            content[i][9] = obj.get("freeznAmount").toString();
            content[i][10] = obj.get("activNum").toString();
            content[i][11] = "V" + obj.get("thisGrade").toString();
            Integer state = Integer.valueOf(obj.get("state").toString());
            content[i][12] = state == 1 ? "正常" : state == 2 ? "禁止登录" : "禁止体现";

            String realName = obj.get("realName").toString();
            realName = "1".equals(realName) ? "已认证" : "0".equals(realName) ? "未认证" : realName;
            content[i][13] = realName;

            String date = obj.get("createTime").toString();
            String dateStr = DateUtils.format(DateUtils.stringToDate(date, DateUtils.DATE_TIME_PATTERN), DateUtils.DATE_TIME_PATTERN);
            content[i][14] = dateStr;

        }
        Workbook workbook = ExcelUtil.generateNewWorkbook(sheetName, title, content);
        ExcelUtil.downLoadByExcel(response, fileName, workbook);
    }


}
